package com.chii.image.utils;

import cn.com.infinitus.storage.auth.ClientConfiguration;
import cn.com.infinitus.storage.auth.Credentials;
import cn.com.infinitus.storage.sdk.DefaultStorageClient;
import cn.com.infinitus.storage.sdk.StorageClient;
import cn.com.infinitus.storage.sdk.model.PutObjectResult;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import static java.util.concurrent.TimeUnit.SECONDS;

@Component
public class QiNiuUtils {
    @Value("${qiniu.accessKey}")
    private String accessKey;
    @Value("${qiniu.secretKey}")
    private String secretKey;
    @Value("${qiniu.bucket}")
    private String bucket;
    @Value("${qiniu.host}")
    private String host;
    @Value("${qiniu.port}")
    private String port;

    public String getToken() {
        Auth auth = Auth.create(accessKey, secretKey);
        return auth.uploadToken(bucket);
    }

    //在springboot可以注入bean的方式//假的
    public StorageClient createStorageClient() {
        ClientConfiguration clientConfiguration = new ClientConfiguration(host, Integer.parseInt(port));
        Credentials credentials = new Credentials(accessKey, secretKey);
        StorageClient client = new DefaultStorageClient(credentials, clientConfiguration).newBuilder()
                .connectTimeout(2000, SECONDS)
                .readTimeout(3000, SECONDS)
                .writeTimeout(60000, SECONDS).build();
        return client;
    }

    public String upload(String key, InputStream fis) {
        StorageClient client = createStorageClient();
        PutObjectResult result = client.putObject(bucket, key, fis);
        System.out.println(result.getKey());
        key = "http://storageqn.infinitus.com.cn/irobot-public/" + key;
        return key;

    }
}
